When a loop variable is not used outside of a loop, it should be declared inside the loop declaration:
- It improves readability. The scope of the variable is clearly defined.
- It reduces the number of mistakes. The variable can’t be accidentally misused outside of the loop.
- Resources are not retained longer than necessary.
Noncompliant code example
void f() {
int i = 0; // Noncompliant: i is not used outside of the loop
for (i = 0; i < 10; ++i) {
std::cout << i << std::endl;
}
}
Compliant solution
void f() {
for (int i = 0; i < 10; ++i) {
std::cout << i << std::endl;
}
}